package com.horse.cloud.gateway.filter;


import com.horse.cloud.data.access.gateway.entity.ClFsgwSystem;
import com.horse.cloud.data.access.gateway.mapperInterface.ClFsgwSystemMapper;
import com.horse.cloud.gateway.constant.MicroServiceRequestConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


/**
 * @create: Created by intelliJ IDEA18.1.3
 * @author: bing.Pan
 * @e-mail: 15923508369@163.com
 * @gmdate: 14/11/2018　14:45　星期三 (dd/MM/YYYY HH:mm)
 * @sidesc:
 */
@Component
public class ExecuteTimeFilter implements GlobalFilter, Ordered {

    @Autowired private ClFsgwSystemMapper clFsgwSystemMapper;
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizeFilter.class);
    private static final String ELAPSED_TIME_BEGIN = MicroServiceRequestConstant.ELAPSED_TIME_BEGIN;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        ClFsgwSystem clFsgwSystem = new ClFsgwSystem();
        List<ClFsgwSystem> list = clFsgwSystemMapper.findListByT(clFsgwSystem);
        System.out.println(list);


        exchange.getAttributes().put(ELAPSED_TIME_BEGIN, System.currentTimeMillis());
        return chain.filter(exchange).then( Mono.fromRunnable(() -> {
            Long startTime = exchange.getAttribute(ELAPSED_TIME_BEGIN);
            long currentTimeMillis = System.currentTimeMillis();
            long executeTime = (currentTimeMillis - startTime) / 1000;
            long fragmentSecond = (currentTimeMillis - startTime) % 1000;
            LOGGER.info("【cloud-gateway】 服务响应耗时 [{}] 秒", String.format("%s.%s",executeTime,fragmentSecond));

        }));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
